package tbalert.web.manager.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import tbalert.hibernate3.Finder;
import tbalert.hibernate3.Updater;
import tbalert.page.Pagination;
import tbalert.web.dao.DwdmDao;
import tbalert.web.dao.RoleDao;
import tbalert.web.entity.Role;
import tbalert.web.manager.RoleMng;

@Transactional
public class RoleMngImpl implements RoleMng {

	@Autowired(required = true)
	private RoleDao roleDao;
	@Autowired(required = true)
	private DwdmDao dwdmDao;

	public Role deleteById(Integer id) {
		if (dwdmDao.getByRole(new Role(id)) != null) {
			return null;
		}
		return roleDao.deleteById(id);
	}

	public Role[] deleteByIds(Integer[] ids) {
		Role[] beans = new Role[ids.length];
		for (int i = 0, len = ids.length; i < len; i++) {
			beans[i] = roleDao.deleteById(ids[i]);
		}
		return beans;
	}

	@Override
	public Role findById(Integer id) {
		return roleDao.findById(id);
	}

	@Override
	public Pagination findRole(Role role, int pageNo, int pageSize) {
		Finder finder = Finder.create("from Role ");
		if (role != null && !StringUtils.isBlank(role.getRoleName())) {
			finder.append("where roleName like :roleName");
			finder.setParam("roleName", "%" + role.getRoleName() + "%");
		}
		return roleDao.find(finder, pageNo, pageSize);
	}

	@Override
	public List<Role> getAll() {
		return roleDao.getAll();
	}

	@Override
	public Role save(Role role) throws HibernateException {
		return roleDao.save(role);
	}

	@Override
	public Role update(Role role) {
		Updater<Role> updater = new Updater<Role>(role);
		return roleDao.updateByUpdater(updater);
	}
}
